const { Buffer } = require('node:buffer')
const { createCipheriv, createDecipheriv, randomBytes } = require('node:crypto')
import { randomUUID } from 'node:crypto'

const keyStr = '110e4a4aeede9845028802131eea0ea6' // 16进制16字节

export function encrypt(text: string) {
  const iv = randomBytes(16) // 初始化向量
  const cipher = createCipheriv('aes-128-cbc', Buffer.from(keyStr, 'hex'), iv)

  let encrypted = cipher.update(text)
  encrypted = Buffer.concat([encrypted, cipher.final()])

  return iv.toString('hex') + ':' + encrypted.toString('base64')
}

export function decrypt(text: string) {
  const ivStr = text.split(':')[0]
  const ciphertext = text.split(':')[1]
  const ciphertextData = Buffer.from(ciphertext, 'base64')
  const iv = Buffer.from(ivStr, 'hex')
  const key = Buffer.from(keyStr, 'hex')

  const decipher = createDecipheriv('aes-128-cbc', key, iv)
  const decoded = decipher.update(ciphertextData)
  const final = decipher.final()

  return Buffer.concat([decoded, final]).toString() // utf-8
}

export function tree2Arr(tree: any[], arr: any[], pid = '') {
  for (let i = 0; i < tree.length; i++) {
    const item = tree[i]

    item.id = randomUUID()
    item.pid = pid
    const children = item.children
    Reflect.deleteProperty(item, 'children')
    arr.push(item)

    if (children?.length > 0) tree2Arr(children, arr, item.id)
  }

  return arr
}
